import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_user_account.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:get/get.dart';

import '../../../bean/bean_category.dart';
import '../../../bean/bean_integral.dart';
import '../../catalogue/catalogue_article_page.dart';
import '../../study/main_video_v2_page.dart';
import '../../topic/topic_select_page.dart';
import '../new/score/mine_my_his_recoder_page.dart';
import 'controller/account_task_details_controller.dart';

///任务详情页面
class AccountTaskDetailsPage extends StatefulWidget {
  final String tag;

  final int taskId;

  const AccountTaskDetailsPage({Key key, this.tag, @required this.taskId})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return AccountTaskDetailsPageState();
  }
}

class AccountTaskDetailsPageState extends State<AccountTaskDetailsPage>
    with SingleTickerProviderStateMixin {
  AccountTaskDetailsController userController;
  String _tag;
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tag = widget.tag;
    userController =
        Get.put(AccountTaskDetailsController(widget.taskId), tag: _tag);
    _tabController = new TabController(length: 3, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffafafa),
      body: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          children: [
            Positioned(
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0xFF90CAF9),
                      Colors.white,
                    ],
                  ),
                ),
              ),
            ),
            Positioned.fill(
              child: Scaffold(
                backgroundColor: Colors.transparent,
                appBar: AppBar(
                  backgroundColor: Colors.transparent,
                  elevation: 0,
                  title: Text("任务详情"),
                ),
                body: RefreshIndicator(
                  notificationPredicate: (ScrollNotification notification) {
                    return true;
                  },
                  onRefresh: () {
                    return Get.find<AccountTaskDetailsController>(tag: _tag)
                        .onRefresh();
                  },
                  child: NestedScrollView(
                    headerSliverBuilder: (
                      BuildContext context,
                      bool innerBoxIsScrolled,
                    ) {
                      return [
                        SliverToBoxAdapter(
                          child: Container(
                            alignment: Alignment.centerLeft,
                            padding: EdgeInsets.only(top: 10, bottom: 10),
                            child: TabBar(
                              indicatorColor: Colors.blue[900],
                              labelColor: Colors.blue[900],
                              isScrollable: true,
                              controller: _tabController,
                              indicatorSize: TabBarIndicatorSize.label,
                              tabs: [
                                Tab(
                                  text: "我的任务",
                                ),
                                Tab(
                                  text: "任务明细",
                                ),
                                Tab(
                                  text: "积分明细",
                                )
                              ],
                            ),
                          ),
                        )
                      ];
                    },
                    body: Container(
                      child: TabBarView(
                        controller: _tabController,
                        children: [
                          buildTaskListWidget(),
                          buildTaskDetailsWidget(),
                          buildAccountWaterWidget(),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///任务列表
  buildTaskListWidget() {
    return GetBuilder(
      id: "taskList",
      tag: _tag,
      builder: (AccountTaskDetailsController controller) {
        List<CategoryBean> categoryList = controller.studyCategoryList;
        TaskBean taskBean = controller.taskBean;
        if (taskBean == null) {
          return SizedBox();
        }
        if (categoryList == null) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: double.infinity,
                padding: EdgeInsets.all(10),
                constraints: BoxConstraints(minHeight: 120),
                margin: EdgeInsets.only(bottom: 8, left: 12, right: 12),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                      colors: [Color(0xFFE3F2FD), Color(0xFFBBDEFB)]),
                  borderRadius: BorderRadius.all(Radius.circular(12)),
                  border: Border.all(
                    color: Colors.white,
                  ),
                ),
                child: Row(
                  children: [
                    SizedBox(
                      width: 8,
                    ),
                    SizedBox(
                      width: 60,
                      height: 60,
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          Positioned.fill(
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              value: taskBean.taskCount / taskBean.taskNumber,
                              backgroundColor: Colors.grey[300],
                            ),
                          ),
                          Text(
                              "${(taskBean.taskCount / taskBean.taskNumber * 100).toStringAsFixed(0)}%")
                        ],
                      ),
                    ),
                    SizedBox(
                      width: 12,
                    ),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            taskBean.taskDetailsRemark,
                            style: TextStyle(
                                fontWeight: FontWeight.w500, fontSize: 16),
                          ),
                          taskBean.goDoing
                              ? ElevatedButton(
                                  onPressed: () async {
                                    if (widget.tag == "taskmin0") {
                                      await Get.to(
                                        () => CatalogueArticleMainPage(
                                          taskId: taskBean.id,
                                        ),
                                      );
                                      controller.onRefresh(click: true);
                                    } else if (widget.tag == "taskmin2") {
                                      await Get.to(
                                        () => VideoStudyMainV2Page(
                                          taskId: taskBean.id,
                                        ),
                                      );
                                      controller.onRefresh(click: true);
                                    }
                                  },
                                  child: Text("立即参与"),
                                )
                              : Container(
                                  child: Text("已完成任务"),
                                ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          );
        }

        int itemCount = categoryList.length;

        String taskDetailsRemark = "";
        bool goDoing = false;
        if (taskBean != null) {
          taskDetailsRemark = taskBean.taskDetailsRemark;
          goDoing = taskBean.goDoing;
        }

        bool initLoading = controller.initLoading;
        bool isLoading = controller.isLoading;
        if (isLoading || initLoading) {
          return Center(child: LoadingWidget());
        }

        if (categoryList.isEmpty) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: () {
                  controller.requestTaskInfo(click: true);
                },
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset(
                      "assets/images/2.0x/home_study.png",
                      width: 33,
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Text(
                      "暂无数据",
                      style: TextStyle(color: Colors.grey),
                    )
                  ],
                ),
              )
            ],
          );
        }

        return Container(
          margin: EdgeInsets.only(bottom: 8, left: 12, right: 12),
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color(0xFFE3F2FD), Color(0xFFBBDEFB)]),
              borderRadius: BorderRadius.all(Radius.circular(12)),
              border: Border.all(
                color: Colors.white,
              )),
          child: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: EdgeInsets.only(bottom: 12, top: 12),
                  child: Row(
                    children: [
                      SizedBox(width: 8),
                      Expanded(
                        child: Container(
                          child: Text(
                            "当前有${categoryList.length}类目可参与",
                            style: TextStyle(
                                fontWeight: FontWeight.w600,
                                color: Colors.black),
                          ),
                        ),
                      ),
                      SizedBox(width: 4),
                      Text(
                        "",
                        style: TextStyle(
                          fontSize: 12,
                          color: Color(0xff777777),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(top: 2),
                        child: Icon(
                          Icons.arrow_forward_ios_outlined,
                          color: Colors.transparent,
                          size: 12,
                        ),
                      ),
                      SizedBox(width: 4),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(left: 12),
                  margin: EdgeInsets.only(bottom: 12),
                  child: Text(taskDetailsRemark),
                ),
                GridView.builder(
                  padding: EdgeInsets.only(left: 8, right: 8),
                  shrinkWrap: true,
                  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                      maxCrossAxisExtent: 200,
                      childAspectRatio: 3 / 2,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10),
                  itemCount: itemCount,
                  itemBuilder: (BuildContext context, int index) {
                    CategoryBean item = categoryList[index];
                    return GestureDetector(
                      onTap: () async {
                        if (!taskBean.goDoing) {
                          return;
                        }
                        await Get.to(
                          () => TopicSelectPage(
                            taskId: taskBean.id,
                            pageTitle: "${item.categoryName}",
                            categoryOne: item.categoryCode,
                          ),
                        );
                        controller.onRefresh(click: true);
                      },
                      child: buildTaskListItemWidget(item, goDoing),
                    );
                  },
                )
              ],
            ),
          ),
        );
      },
    );
  }

  ///构建任务条目
  buildTaskListItemWidget(item, bool goDoing) {
    IconData iconData = Icons.book;
    String categrtyImg = item.categrtyImg;

    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
              color: Colors.white,
              padding: EdgeInsets.only(left: 12, top: 12, right: 2),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Container(
                            height: 58,
                            margin: EdgeInsets.only(right: 8),
                            child: Row(
                              children: [
                                ClipOval(
                                  child: Container(
                                    color: Color(0xFFE3F2FD),
                                    padding: EdgeInsets.all(4),
                                    child: Stack(
                                      alignment: Alignment.center,
                                      children: [
                                        categrtyImg == null ||
                                                categrtyImg.isEmpty
                                            ? Icon(
                                                iconData,
                                                color: Colors.blue[900],
                                                size: 16,
                                              )
                                            : CachedNetworkImage(
                                                imageUrl: categrtyImg,
                                                width: 26,
                                                height: 26,
                                              ),
                                      ],
                                    ),
                                  ),
                                )
                              ],
                            ),
                          )
                        ],
                      ),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.center,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Row(
                              children: [
                                Container(
                                  margin: EdgeInsets.only(top: 2),
                                  child: ClipOval(
                                    child: Container(
                                      width: 11,
                                      height: 11,
                                      child: Icon(
                                        Icons.code,
                                        color: Colors.white,
                                        size: 6,
                                      ),
                                      color: Colors.blue[900],
                                    ),
                                  ),
                                ),
                                SizedBox(width: 8),
                                Text(
                                  "答题学习",
                                  style: TextStyle(
                                      fontSize: 10, color: Color(0xff666666)),
                                ),
                              ],
                            ),
                            SizedBox(height: 2),
                            Text(
                              item.categoryName,
                              style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.black),
                            ),
                            Text(
                              goDoing ? "快点击参与任务吧" : "已完成任务",
                              style: TextStyle(
                                  fontSize: 12,
                                  color: goDoing ? Colors.blue : Colors.red),
                            ),
                          ],
                        ),
                      ),
                      goDoing
                          ? Icon(
                              Icons.arrow_forward_ios,
                              size: 12,
                              color: Colors.blue,
                            )
                          : SizedBox()
                    ],
                  ),
                ],
              ))
        ],
      ),
    );
  }

  ///任务列表
  buildTaskDetailsWidget() {
    return GetBuilder(
      id: "taskDetailsList",
      tag: _tag,
      builder: (AccountTaskDetailsController controller) {
        List<TaskBeanDetails> taskDetailsList = controller.taskDetailsList;

        bool taskDetailsLoading = controller.taskDetailsLoading;
        if (taskDetailsLoading) {
          return Center(
            child: LoadingWidget(),
          );
        }

        if (taskDetailsList.isEmpty) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: () {
                  controller.requestTaskDetailsList(click: true);
                },
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset(
                      "assets/images/2.0x/home_study.png",
                      width: 33,
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Text(
                      "暂无数据",
                      style: TextStyle(color: Colors.grey),
                    )
                  ],
                ),
              )
            ],
          );
        }

        return Container(
          margin: EdgeInsets.only(bottom: 8, left: 12, right: 12),
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color(0xFFE3F2FD), Color(0xFFBBDEFB)]),
              borderRadius: BorderRadius.all(Radius.circular(12)),
              border: Border.all(
                color: Colors.white,
              )),
          child: ListView.builder(
            itemCount: taskDetailsList.length,
            itemBuilder: (BuildContext context, int index) {
              TaskBeanDetails item = taskDetailsList[index];
              bool isShowTitle = true;
              bool isShowBottomTitle = true;
              int type = item.type;
              int itemId = int.parse(item.itemId);
              Color textColor = Colors.grey;
              String preText = "";
              if (type == 0) {
                textColor = Colors.red;
                preText = "阅读";
              } else if (type == 2) {
                textColor = Colors.blue;
                preText = "视频";
              } else if (type == 1) {
                textColor = Colors.deepOrange;
                preText = "练习";
              }

              if (index > 0) {
                TaskBeanDetails preItem = taskDetailsList[index - 1];
                if (item.createTimeStr == preItem.createTimeStr) {
                  isShowTitle = false;
                }
              }
              if (index < taskDetailsList.length - 1) {
                TaskBeanDetails netxItem = taskDetailsList[index + 1];
                if (item.createTimeStr == netxItem.createTimeStr) {
                  isShowBottomTitle = false;
                }
              }
              return Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    isShowTitle
                        ? Padding(
                            padding: EdgeInsets.only(bottom: 12, top: 12),
                            child: Row(
                              children: [
                                SizedBox(width: 8),
                                Container(
                                  child: Text(
                                    item.createTimeStr,
                                    style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        color: Colors.black),
                                  ),
                                ),
                              ],
                            ),
                          )
                        : SizedBox(),
                    Container(
                      color: Colors.white,
                      padding: EdgeInsets.only(left: 12, top: 12, right: 12),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text(
                                      item.remark,
                                      style: TextStyle(
                                          fontSize: 14, color: Colors.black),
                                    ),
                                    SizedBox(
                                      height: 8,
                                    ),
                                    Text(
                                      item.itemName,
                                      style: TextStyle(
                                          fontSize: 12,
                                          color: Color(0xff666666)),
                                    ),
                                    SizedBox(
                                      height: 8,
                                    ),
                                  ],
                                ),
                              ),
                              GestureDetector(
                                onTap: () {
                                  if (type == 1) {
                                    NavigatorUtils.pushPage(
                                      context,
                                      MineMyScoreHisRecoderPage(
                                        extractingId: itemId,
                                      ),
                                    );
                                  }
                                },
                                child: Text(
                                  "$preText ",
                                  style: TextStyle(
                                      color: textColor,
                                      fontSize: 14,
                                      fontWeight: FontWeight.normal),
                                ),
                              )
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              Text(
                                item.createTime,
                                style: TextStyle(
                                    fontSize: 12, color: Color(0xff666666)),
                              ),
                            ],
                          ),
                          Container(
                            width: double.infinity,
                            height: 1,
                            color: Color(0xffeeeeee),
                            margin: EdgeInsets.only(top: 10),
                          )
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        );
      },
    );
  }

  ///积分收支明细
  buildAccountWaterWidget() {
    return GetBuilder(
      id: "accountWater",
      tag: _tag,
      builder: (AccountTaskDetailsController controller) {
        List<IntegralStatBean> waterList = controller.waterList;

        bool waterLoading = controller.waterLoading;
        if (waterLoading) {
          return Center(
            child: LoadingWidget(),
          );
        }

        if (waterList.isEmpty) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: () {
                  controller.requestWaterList(click: true);
                },
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset(
                      "assets/images/2.0x/home_study.png",
                      width: 33,
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    Text(
                      "暂无数据",
                      style: TextStyle(color: Colors.grey),
                    )
                  ],
                ),
              )
            ],
          );
        }

        return Container(
          margin: EdgeInsets.only(bottom: 8, left: 12, right: 12),
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color(0xFFE3F2FD), Color(0xFFBBDEFB)]),
              borderRadius: BorderRadius.all(Radius.circular(12)),
              border: Border.all(
                color: Colors.white,
              )),
          child: ListView.builder(
            itemCount: waterList.length,
            itemBuilder: (BuildContext context, int index) {
              IntegralStatBean item = waterList[index];
              bool isShowTitle = true;
              bool isShowBottomTitle = true;
              Color textColor = Colors.grey;
              String preText = "";

              if (index > 0) {
                IntegralStatBean preItem = waterList[index - 1];
                if (item.createTimeStr == preItem.createTimeStr) {
                  isShowTitle = false;
                }
              }
              if (index < waterList.length - 1) {
                IntegralStatBean netxItem = waterList[index + 1];
                if (item.createTimeStr == netxItem.createTimeStr) {
                  isShowBottomTitle = false;
                }
              }
              return Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    isShowTitle
                        ? Padding(
                            padding: EdgeInsets.only(bottom: 12, top: 12),
                            child: Row(
                              children: [
                                SizedBox(width: 8),
                                Container(
                                  child: Text(
                                    item.createTimeStr,
                                    style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        color: Colors.black),
                                  ),
                                ),
                              ],
                            ),
                          )
                        : SizedBox(),
                    Container(
                        color: Colors.white,
                        padding: EdgeInsets.only(left: 12, top: 12, right: 12),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Text(
                                        item.remark,
                                        style: TextStyle(
                                            fontSize: 14, color: Colors.black),
                                      ),
                                      SizedBox(
                                        height: 8,
                                      ),
                                      Text(
                                        item.createTime,
                                        style: TextStyle(
                                            fontSize: 12,
                                            color: Color(0xff666666)),
                                      )
                                    ],
                                  ),
                                ),
                                Text(
                                  "$preText ${item.videoIntegral}分",
                                  style: TextStyle(
                                      color: textColor,
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600),
                                )
                              ],
                            ),
                            Container(
                              width: double.infinity,
                              height: 1,
                              color: Color(0xffeeeeee),
                              margin: EdgeInsets.only(top: 10),
                            )
                          ],
                        ))
                  ],
                ),
              );
            },
          ),
        );
      },
    );
  }

  buildItemClass(String title, String iconData, Widget page) {
    return Expanded(
      child: GestureDetector(
        onTap: () {
          NavigatorUtils.pushPage(context, page);
        },
        child: Container(
          margin: EdgeInsets.only(top: 10, bottom: 10),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(
                "$iconData.png",
                width: 22,
              ),
              SizedBox(
                height: 4,
              ),
              Text(
                title,
                style: TextStyle(fontSize: 12),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
